package com.common.baselibrary.progress;

import com.common.baselibrary.request.BaseCallModel;
import com.common.baselibrary.request.ErrorResponse;
import com.common.baselibrary.request.ResultException;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
//        Log.d("response>>", response);
        //只解析data字段
        BaseCallModel httpResult = gson.fromJson(response, BaseCallModel.class);
        if (httpResult.isSuccess()) {
            return gson.fromJson(response, type);
        } else {
            ErrorResponse errorResponse = gson.fromJson(response, ErrorResponse.class);
            throw new ResultException(errorResponse.getMsg(), errorResponse.getCode());
        }
    }
}
